<?php

namespace App\Services;

use App\UsersOrders;
use Carbon\Carbon;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Illuminate\Support\Facades\DB;

class AutoService
{
    /**
     * 12点执行发放饭点打卡活动奖金  12点执行
     */
    public static function mealLotGrant()
    {
        set_time_limit(3600);
        if (\DB::table('meals_grant_log')->where('date', date('Y-m-d'))->count()) {
            return false;
        }
        InterfaceLog('mealLotGrant', '12点执行发放饭点打卡活动奖金');
//        添加明日记录
        \DB::table('meals')->insert(['date' => date('Y-m-d', strtotime('+1 day', time())), 'created_at' => getDt(), 'updated_at' => getDt()]);
        $list = \DB::table('meals_join')->where('date', date('Y-m-d'))->get()->toArray();
        $count = 0;
        $amount = 0;
        if (count($list)) {
            foreach ($list as $item) {
                if ($item->is_sign == 1) {
                    $count += $item->amount;
                }
                $amount += $item->amount;
            }
        }
        try {
            $cacluAmount = 0;
            $list1 = \DB::table('meals_join')->where('date', date('Y-m-d'))->where('is_sign', 1)->get()->toArray();
            \DB::beginTransaction();
            if( $amount > 0 && count($list1) > 0 ){
                foreach ($list1 as $k => $item) {
                    //发放记录
                    if ($k + 1 == count($list1)) {
                        $value = $amount - $cacluAmount;
                    } else {
                        $value = round($item->amount / $count * $amount, 2);
                    }
    //                更新实际获得金额
                    \DB::table('meals_join')->where('id', $item->id)->update(['get_amount'=>$value, 'updated_at'=>getDt()]);
    //                更新用户余额
                    UserService::userBalanceUpdate($item->uid, $value, 4, $item->id, 1);
                    $cacluAmount += $value;
                }
            }else{
                if( $amount > 0 && count($list1) <= 0 ){
                    $log = [
                        ['type'=>11, 'type_value'=>'营销收入', 'title'=>'打卡回收', 'order_no'=>getOrderNo(999999, 5), 'amount'=>$amount, 'created_at'=>date('Y-m-d H:i:s')],
                    ];
    //                插入平台对账单
                    \DB::table('platform_balance_log')->insert($log);
                }
            }
            
            \DB::table('meals_grant_log')->insert(['date' => date('Y-m-d'), 'amount' => $amount, 'created_at' => getDt()]);
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
        }

    }

    /**
     * 订单自动过期:30分钟    1分钟执行一次
     */
    public static function orderAutoCancel()
    {
        InterfaceLog('orderAutoCancel', '订单自动过期');
        $list = \DB::table('users_orders')->whereIn('status', [0, 10])->where('overdue', '<', date('Y-m-d H:i:s'))
            ->select(['id', 'sub_id'])->get()->toArray();
        if (count($list)) {
            foreach ($list as $item) {
                try {
                    \DB::beginTransaction();
                    //取消订单
                    \DB::table('users_orders')->where('id', $item->id)->update(['status' => 60, 'updated_at' => getDt()]);
                    //任务剩余单数回滚
                    \DB::table('subsidy')->where('id', $item->sub_id)->increment('current_rest');
                    \DB::commit();
                } catch (\Exception $exception) {
                    \DB::rollBack();
                }
            }

        }
    }

    /**
     * 初审上传提醒:20分钟    1分钟执行一次
     */
    public static function checkOrderOverdue()
    {
        InterfaceLog('checkOrderOverdue', '初审上传提醒');
        // $list = \DB::table('users_orders')->where('status', 0)->where('is_overdue_remind', 0)->where('overdue', '<', date('Y-m-d H:i:s', time()+60*10))->select(['id', 'uid'])->limit(20)->get()->toArray();
        $list = UsersOrders::whereIn('status', [0, 10])->where('is_overdue_remind', 0)->where('overdue', '<', date('Y-m-d H:i:s', time()+60*10))->select(['id', 'uid', 'store_info_id', 'sub_id', 'overdue'])->limit(20)->get();
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    \DB::beginTransaction();
                    //已提醒订单
                    \DB::table('users_orders')->where('id', $item->id)->update(['is_overdue_remind' => 1, 'updated_at' => getDt()]);
                    //发送消息
                    UserService::sendMiniSoftMsg($item->user->openid, 3, "/pages/order/uploadone?plate={$item->storeInfo->type}&id={$item->id}", [
                        "thing1"=>['value'=>mb_substr($item->storeInfo->title." 满{$item->subsidy->max_money}返{$item->subsidy->return_money}", 0, 19)],
                        "time2"=>['value'=>date('H:i', strtotime($item->overdue))],
                        "thing3"=>['value'=>"订单即将过期，点击查看详情，上传初审"],
                    ]);
                    
                    \DB::commit();
                } catch (\Exception $exception) {
                    \DB::rollBack();
                }
            }

        }
    }

    /**
     * 订单初审通过(复审上传)提醒:    1分钟执行一次
     */
    public static function orderFirstOkRemind()
    {
        InterfaceLog('orderFirstOkRemind', '订单初审通过提醒');
        $list = UsersOrders::where('status', 25)->where('is_first_remind', 0)->whereIn('good_comment_type', [1,2])->select(['id', 'uid', 'store_info_id', 'sub_id'])->limit(30)->get();
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    \DB::beginTransaction();
                    //已提醒订单
                    \DB::table('users_orders')->where('id', $item->id)->update(['is_first_remind' => 1, 'updated_at' => getDt()]);
                    //发送消息
                    UserService::sendMiniSoftMsg($item->user->openid, 7, "/pages/order/uploadtwo?plate={$item->storeInfo->type}&id={$item->id}", [
                        "thing1"=>['value'=>mb_substr($item->storeInfo->title." 满{$item->subsidy->max_money}返{$item->subsidy->return_money}", 0, 19)],
                        "thing2"=>['value'=>"您的订单已通过初审，点击详情上传复审截图"],
                        "time3"=>['value'=>date("Y-m-d 16:00:00", time()+3600*24)],
                        "thing4"=>['value'=>"为避免订单过期，请及时上传复审"],
                    ]);
                    
                    \DB::commit();
                } catch (\Exception $exception) {
                    \DB::rollBack();
                    var_dump($exception->getMessage());
                }
            }
        }
    }

    /**
     * 订单初审未通过提醒:    1分钟执行一次
     */
    public static function orderFirstFailRemind()
    {
        InterfaceLog('orderFirstFailRemind', '订单初审未通过提醒');
        $list = UsersOrders::where('status', 10)->where('is_first_fail_remaid', 0)->select(['id', 'uid', 'store_info_id', 'sub_id', 'fail_reason'])->limit(30)->get();
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    \DB::beginTransaction();
                    //已提醒订单
                    \DB::table('users_orders')->where('id', $item->id)->update(['is_first_fail_remaid' => 1, 'updated_at' => getDt()]);
                    //发送消息
                    UserService::sendMiniSoftMsg($item->user->openid, 4, "/pages/order/uploadone?plate={$item->storeInfo->type}&id={$item->id}", [
                        "thing7"=>['value'=>mb_substr($item->storeInfo->title." 满{$item->subsidy->max_money}返{$item->subsidy->return_money}", 0, 19)],
                        "thing4"=>['value'=>$item->fail_reason],
                        "time5"=>['value'=>getDt()],
                        "thing6"=>['value'=>"请核实信息，重新上传"],
                    ]);
                    
                    \DB::commit();
                } catch (\Exception $exception) {
                    \DB::rollBack();
                }
            }

        }
    }

    /**
     * 订单复审未通过提醒:    1分钟执行一次
     */
    public static function orderSecondFailRemind()
    {
        InterfaceLog('orderSecondFailRemind', '订单复审未通过提醒');
        $list = UsersOrders::where('status', 30)->where('is_second_fail_remaid', 0)->select(['id', 'uid', 'store_info_id', 'sub_id', 'fail_reason'])->limit(30)->get();
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    \DB::beginTransaction();
                    //已提醒订单
                    \DB::table('users_orders')->where('id', $item->id)->update(['is_second_fail_remaid' => 1, 'updated_at' => getDt()]);
                    //发送消息
                    UserService::sendMiniSoftMsg($item->user->openid, 4, "/pages/order/uploadtwo?plate={$item->storeInfo->type}&id={$item->id}", [
                        "thing7"=>['value'=>mb_substr($item->storeInfo->title." 满{$item->subsidy->max_money}返{$item->subsidy->return_money}", 0, 19)],
                        "thing4"=>['value'=>$item->fail_reason],
                        "time5"=>['value'=>getDt()],
                        "thing6"=>['value'=>"请核实信息，重新上传"],
                    ]);
                    
                    \DB::commit();
                } catch (\Exception $exception) {
                    \DB::rollBack();
                }
            }

        }
    }

    /**
     * 订单完成提醒:    1分钟执行一次
     */
    public static function orderCompleteRemind()
    {
        InterfaceLog('orderCompleteRemind', '订单完成提醒');
        $list = UsersOrders::where('status', 50)->where('is_complete_remind', 0)->select(['id', 'uid', 'store_info_id', 'sub_id', 'fail_reason'])->limit(30)->get();
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    \DB::beginTransaction();
                    //已提醒订单
                    \DB::table('users_orders')->where('id', $item->id)->update(['is_complete_remind' => 1, 'updated_at' => getDt()]);
                    //发送消息
                    UserService::sendMiniSoftMsg($item->user->openid, 5, "", [
                        "phrase6"=>['value'=>"已完成"],
                        "thing8"=>['value'=>mb_substr($item->storeInfo->title." 满{$item->subsidy->max_money}返{$item->subsidy->return_money}", 0, 19)],
                        "date4"=>['value'=>getDt()],
                        "thing7"=>['value'=>"祝您用餐愉快"],
                    ]);
                    
                    \DB::commit();
                } catch (\Exception $exception) {
                    \DB::rollBack();
                }
            }

        }
    }

    /**
     * 订单次日13点前未提交复审提醒:
     */
    public static function orderTomoNotSubmitAudit()
    {
        set_time_limit(3600);
        InterfaceLog('orderTomoNotSubmitAudit', '订单次日13点前未提交复审提醒');
        $list = UsersOrders::whereIn('status', [25,30])->where('overdue', '<', date('Y-m-d 16:00:00'))->select(['id', 'uid', 'store_info_id', 'sub_id'])->get();
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    //发送消息
                    UserService::sendMiniSoftMsg($item->user->openid, 6, "/pages/order/uploadtwo?plate={$item->storeInfo->type}&id={$item->id}", [
                        "thing2"=>['value'=>mb_substr($item->storeInfo->title." 满{$item->subsidy->max_money}返{$item->subsidy->return_money}", 0, 19)],
                        "date3"=>['value'=>"16:00"],
                        "thing5"=>['value'=>"订单将于3小时后过期，请及时上传评价截图"],
                    ]);
                } catch (\Exception $exception) {
                    InterfaceLog('orderTomoNotSubmitAudit', $exception->getMessage());
                }
            }

        }
    }

    /**
     * 复审即将逾期通知提醒:14:00  21:00
     */
    public static function orderNotSettleNotify()
    {
        set_time_limit(3600);
        InterfaceLog('orderNotSettleNotify', '复审即将逾期通知提醒');
        $list = UsersOrders::whereIn('status', [35, 40])->select(['store_uid', DB::raw('count(*) as count')])->groupBy('store_uid')->get();
        
        if ($list->isNotEmpty()) {
            foreach ($list as $item) {
                try {
                    //发送消息
                    UserService::sendMiniSoftMsg($item->storeUser->openid, 2, "pages/store/orderlist?type=1", [
                        "thing1"=>['value'=>"好评返现"],
                        "thing2"=>['value'=>$item->count."个"],
                        "thing4"=>['value'=>"昨日订单24点前未结算记逾期"],
                        "thing3"=>['value'=>"订单逾期未处理，将影响用户正常下单"],
                    ]);
                } catch (\Exception $exception) {
                    InterfaceLog('orderNotSettleNotify', $exception->getMessage());
                }
            }

        }
    }

    /**
     * 任务自动过期    00：00执行
     */
    public static function subAutoCancel()
    {
        InterfaceLog('subAutoCancel', '任务自动过期');
        $ids = \DB::table('subsidy')->where('status', 1)->where('overdue', '<=', date('Y-m-d'))->pluck('id');
        if (count($ids)) {
            \DB::table('subsidy')->whereIn('id', $ids)->update(['status' => 2, 'updated_at' => getDt()]);
        }

    }

    /**
     * 任务每日单数重置    任务自动过期执行后执行
     */
    public static function subCountReset()
    {
        InterfaceLog('subAutoCancel', '任务每日单数重置');
        $ids = \DB::table('subsidy')->where('status', 1)->pluck('single_day_count', 'id')->toArray();
        if (count($ids)) {
            foreach ($ids as $k => $value) {
                \DB::table('subsidy')->where('id', $k)->update(['current_rest' => $value, 'updated_at' => getDt()]);
            }

        }

    }

    /**
     * 订单初审核阿里自动审核    1分钟执行一次
     */
    public static function orderAudit()
    {
        InterfaceLog('orderAudit', '订单自动审核');
        $list = \DB::table('users_orders')->where([
            ['status', 20],
            ['is_need_ali_audit', 0],
            ['sub_time1', '<', date('Y-m-d H:i:s')],
        ])->select(['good_comment_type', 'id', 'amount', 'user_order_no', 'imgs', 'store_title', 'created_at', 'max_money'])->limit(10)->get()->toArray();
        if (count($list)) {
            foreach ($list as $item) {
                // if( $item->amount < $item->max_money ){
                //     \DB::table('users_orders')->where('id', $item->id)->update(['status' => 10, 'updated_at' => getDt()]);
                //     continue;
                // }
                $imgs = explode(',', $item->imgs);
                $arr = [];
                if (is_array($imgs) && count($imgs)) {
                    try{
                        foreach ($imgs as $img) {
                            $resultWords = imgRecognition(strpos($img, 'http') === false ? $img:$img);
                            if ($resultWords) {
                                $arr = array_merge($arr, $resultWords);
                            }
                        }
                    } catch (\Exception $e) {
                        InterfaceLog('orderAudit', '图片识别异常'.$e->getMessage(), 2);
                        continue;
                    }
                    
                }
                $msg = "订单截图有误";
                if (count($arr)) {
                    
                    $result = autoAudit($arr, $item->user_order_no, $item->store_title, $item->amount, date('Y-m-d', strtotime($item->created_at)), $msg);
                    if ($result) {
                        if ($item->good_comment_type == 0) {
                            \DB::table('users_orders')->where('id', $item->id)->update([
                                'status' => 35, 'updated_at' => getDt(), 'is_need_ali_audit' => 1
                            ]);
                        } else {
                            \DB::table('users_orders')->where('id', $item->id)->update([
                                'status' => 25, 'updated_at' => getDt(), 'is_need_ali_audit' => 1,'overdue'=>date('Y-m-d 15:59:59', time()+3600*24)
                            ]);
                        }

                        continue;
                    }
                    DistLog($arr, $item->id);
                    // else{
                    //     //识图失败
                    //     if (is_array($imgs) && count($imgs)) {
                    //         try{
                    //             foreach ($imgs as $img) {
                    //                 $resultWords = imgRecognition1(strpos($img, 'http') === false ? $img:$img);
                    //                 if ($resultWords) {
                    //                     $arr = array_merge($arr, $resultWords);
                    //                 }
                    //             }
                    //         } catch (\Exception $e) {
                    //             InterfaceLog('orderAudit', '图片识别异常'.$e->getMessage(), 2);
                    //             continue;
                    //         }
                            
                    //     }
                    //     $result = autoAudit($arr, $item->user_order_no, $item->store_title, $item->amount, date('Y-m-d', strtotime($item->created_at)), $msg);
                    //     if ($result) {
                    //         if ($item->good_comment_type == 0) {
                    //             \DB::table('users_orders')->where('id', $item->id)->update([
                    //                 'status' => 40, 'updated_at' => getDt(), 'is_need_ali_audit' => 1
                    //             ]);
                    //         } else {
                    //             \DB::table('users_orders')->where('id', $item->id)->update([
                    //                 'status' => 25, 'updated_at' => getDt(), 'is_need_ali_audit' => 1,'overdue'=>date('Y-m-d 15:59:59', time()+3600*24)
                    //             ]);
                    //         }

                    //         continue;
                    //     }
                    // }
                }
                \DB::table('users_orders')->where('id', $item->id)->update(['status' => 10, 'updated_at' => getDt(), 'fail_reason'=>$msg, 'overdue'=>date('Y-m-d H:i:s', time()+1800), 'is_overdue_remind'=>0]);
            }
        }
    }

    /**
     * 订单初审核阿里自动审核    1分钟执行一次
     */
    public static function orderAudit1()
    {
        $list = \DB::table('users_orders')->where([
            ['id', 238]])->select(['good_comment_type', 'id', 'amount', 'user_order_no', 'imgs', 'store_title', 'created_at', 'max_money'])->limit(10)->get()->toArray();
        if (count($list)) {
            foreach ($list as $item) {
                // if( $item->amount < $item->max_money ){
                //     \DB::table('users_orders')->where('id', $item->id)->update(['status' => 10, 'updated_at' => getDt(), 'fail_reason'=>"实付金额低于满减金额"]);
                //     continue;
                // }
                $imgs = explode(',', $item->imgs);
                $arr = [];
                if (is_array($imgs) && count($imgs)) {
                    try{
                        foreach ($imgs as $img) {
                            $resultWords = imgRecognition(strpos($img, 'http') === false ? $img:$img);
                            if ($resultWords) {
                                $arr = array_merge($arr, $resultWords);
                            }
                        }
                    } catch (\Exception $e) {
                        InterfaceLog('orderAudit', '图片识别异常'.$e->getMessage(), 2);
                        continue;
                    }
                    
                }
                // var_dump($arr);exit;
                $msg = "订单截图有误";
                if (count($arr)) {
                    DistLog($arr, $item->id);exit;
                    $result = autoAudit($arr, $item->user_order_no, $item->store_title, $item->amount, date('Y-m-d', strtotime($item->created_at)), $msg);
                    // if ($result) {
                    //     if ($item->good_comment_type == 0) {
                    //         \DB::table('users_orders')->where('id', $item->id)->update([
                    //             'status' => 40, 'updated_at' => getDt(), 'is_need_ali_audit' => 1
                    //         ]);
                    //     } else {
                    //         \DB::table('users_orders')->where('id', $item->id)->update([
                    //             'status' => 25, 'updated_at' => getDt(), 'is_need_ali_audit' => 1,'overdue'=>date('Y-m-d 15:59:59', time()+3600*24)
                    //         ]);
                    //     }

                    //     continue;
                    // }
                }
                // \DB::table('users_orders')->where('id', $item->id)->update(['status' => 10, 'updated_at' => getDt(), 'fail_reason'=>$msg, 'overdue'=>date('Y-m-d H:i:s', time()+1800), 'is_overdue_remind'=>0]);
            }
        }
    }

    /**
     * 订单次日16点前未提交评价图则取消    16:00执行一次
     */
    public static function orderAuditCancel()
    {
        InterfaceLog('orderAuditCancel', '订单次日16点前未提交评价图则取消');

        $list = \DB::table('users_orders')->whereIn('status', [25,30,32])->where('overdue', '<', date('Y-m-d 16:00:00'))
            ->select(['id', 'sub_id'])->get()->toArray();
        if (count($list)) {
            foreach ($list as $item) {
                \DB::table('users_orders')->where('id', $item->id)->update(['status' => 60, 'updated_at' => getDt()]);
            }

        }

    }

    /**
     * 计算前一天对账明细    00:00
     */
    public static function PlatformDayBalanceLog()
    {
        InterfaceLog('PlatformDayBalanceLog', '计算前一天对账明细');
        set_time_limit(3600);
        //检查是否已存在记录
        $date = date('Y-m-d', strtotime('-1 day', time()));
        $data = \DB::table('platform_balance_day_log')->where('day', $date)->count();
        if (!$data) {
            $list = \DB::table('platform_balance_log')->whereDate('created_at', $date)->select(['type', 'amount'])->get()->toArray();
            $in = $out = $inCount = $outCount = 0;
            foreach ($list as $item) {
                if (in_array($item->type, [1, 6, 7, 9])) {
                    $in += $item->amount;
                    $inCount++;
                } else {
                    $out += $item->amount;
                    $outCount++;
                }
            }
            \DB::table('platform_balance_day_log')->insert([
                'in' => $in,
                'out' => $out,
                'in_num' => $inCount,
                'out_num' => $outCount,
                'day' => $date,
                'created_at' => getDt(),
            ]);
        }
    }

    /**
     * 计算今天之前当月对账明细    00:00
     */
    public static function PlatformMonthBalanceLog()
    {
        InterfaceLog('PlatformMonthBalanceLog', '计算今天之前当月对账明细');
        set_time_limit(3600);
        //检查是否已存在记录
        $month = date('Y-m-01', strtotime('-1 day', time()));
        $year = date('Y', strtotime('-1 day', time()));
        $m = date('m', strtotime('-1 day', time()));
        $data = \DB::table('platform_balance_month_log')->where('month', $month)->count();
        $list = \DB::table('platform_balance_log')
            ->whereMonth('created_at', $m)->whereYear('created_at', $year)->select(['type', 'amount'])->get()->toArray();
        $in = $out = $inCount = $outCount = 0;
        foreach ($list as $item) {
            if (in_array($item->type, [1, 6, 7, 9])) {
                $in += $item->amount;
                $inCount++;
            } else {
                $out += $item->amount;
                $outCount++;
            }
        }
        $log = [
            'in' => $in,
            'out' => $out,
            'in_num' => $inCount,
            'out_num' => $outCount,
            'month' => $month,
        ];
        if ($data) {
            \DB::table('platform_balance_month_log')->where('month', $month)->update(array_merge($log, ['updated_at' => getDt()]));
        } else {
            \DB::table('platform_balance_month_log')->insert(array_merge($log, ['created_at' => getDt()]));
        }


    }

    /**
     * 计算平台余额   每分钟执行
     */
    public static function cacluPlatformBalance()
    {
        set_time_limit(60);
        InterfaceLog('cacluPlatformBalance', '计算平台余额');
        $balanceLog = \DB::table('platform_balance_log')->orderBy('count', 'desc')->where('status', 1)->select(['balance', 'count'])->first();
        if( $balanceLog ){
            $balance = $balanceLog->balance;
            $count = $balanceLog->count+1;
        }else{
            $balance = 0;
            $count = 1;
        }
        for ($i = 0; $i < 60; $i++) {
            $data = \DB::table('platform_balance_log')->orderBy('id', 'asc')->where('status', 0)->first();
            if( $data ){
                if (in_array($data->type, [1, 6, 7, 9])) {
                    \DB::table('platform_balance_log')->where('id', $data->id)->where('status', 0)->update(['updated_at' => getDt(), 'balance' => $balance + $data->amount, 'status'=>1,'count'=>$count]);
                    $balance += $data->amount;
                } else {
                    \DB::table('platform_balance_log')->where('id', $data->id)->where('status', 0)->update(['updated_at' => getDt(), 'balance' => $balance - $data->amount, 'status'=>1,'count'=>$count]);
                    $balance -= $data->amount;
                }
                $count ++;
            }
        }

    }

    /**
     * 计算用户余额   每分钟执行
     */
    public static function cacluUserBalance()
    {
        set_time_limit(60);
        InterfaceLog('cacluUserBalance', '重新计算用户余额');

        for ($i = 0; $i < 30; $i++) {
            $data = \DB::table('users_balance_logs')->orderBy('id', 'asc')->where('is_caclu1', 0)->where('status', 1)->first();
            if( $data ){
                $balanceLog = \DB::table('users_balance_logs')->orderBy('count', 'desc')
                    ->where('is_caclu1', 1)->where('status', 1)->where('uid', $data->uid)->select(['balance', 'count'])->first();
                if( $balanceLog ){
                    $balance = $balanceLog->balance;
                    $count = $balanceLog->count+1;
                }else{
                    $balance = 0;
                    $count = 1;
                }
                
                // var_dump($balance);exit;
                if (in_array($data->type, [1, 2, 3, 4, 6])) {
                    \DB::table('users_balance_logs')->where('id', $data->id)->where('is_caclu1', 0)->update(['updated_at' => getDt(), 'balance' => $balance + $data->money, 'is_caclu1'=>1,'count'=>$count]);
                } else {
                    \DB::table('users_balance_logs')->where('id', $data->id)->where('is_caclu1', 0)->update(['updated_at' => getDt(), 'balance' => $balance - $data->money, 'is_caclu1'=>1,'count'=>$count]);
                }
            }
        }
    }

    /**
     * 用户自动过期
     */
    public static function userAutoOverdue(){
        InterfaceLog('userAutoOverdue', '用户自动过期');
        $ids = \DB::table('users')->where('vip_status', 1)->where('vip_overdue', '<', date('Y-m-d H:i:s'))->pluck('id');
        if (count($ids)) {
            \DB::table('users')->whereIn('id', $ids)->update(['vip_status' => 0, 'updated_at' => getDt()]);
        }
    }

    /**
     * 提现结果查询    1分钟执行一次
     */
    public static function withdrawalResultCheck()
    {
        set_time_limit(60);
        InterfaceLog('withdrawalResultCheck', '提现结果查询');
        $config = config('wechat.payment.default');
        $app = Factory::payment($config);
        for ($i=0; $i < 20; $i++) { 
            $data = \DB::table('users_withdrawal')->where('status', 1)->orderBy('id', 'asc')
            ->select(['id', 'transaction_no'])->first();
            if( !$data ){
                sleep(1);
            }else{
                $res = $app->transfer->queryBalanceOrder($data->transaction_no);
                if( !isset($res['return_code']) || !isset($res['result_code']) ){
                    continue;
                }
                if( $res['return_code'] == 'SUCCESS' ){
                    
                    if( isset($res['status']) && $res['status'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS' ){
                        //成功
                        $paymentService = new PaymentService();
                        $paymentService->withdrawalResult($data->transaction_no, 1, isset($res['detail_id'])?$res['detail_id']:'');
                        continue;
                    }elseif( ( $res['result_code'] == 'FAIL' && !isset($res['status']) ) || ( isset($res['status']) && $res['status'] == 'FAILED' ) ){
                        //失败
                        $paymentService = new PaymentService();
                        $paymentService->withdrawalResult($data->transaction_no, 0, isset($res['detail_id'])?$res['detail_id']:'');
                        continue;
                    }elseif( isset($res['status']) && $res['status'] == 'PROCESSING' ){
                        //处理中
                        \DB::table('users_withdrawal')->where('id', $data->id)->update(['status'=>4, 'updated_at'=>getDt(), 'wx_no'=>isset($res['detail_id'])?$res['detail_id']:'']);
                        continue;
                    }
                }
            }
        }
    }

    /**
     * 微信提现处理中的结果查询    1分钟执行一次
     */
    public static function withdrawalProcessingResultCheck()
    {
        set_time_limit(60);
        InterfaceLog('withdrawalProcessingResultCheck', '微信提现处理中的结果查询');
        $config = config('wechat.payment.default');
        $app = Factory::payment($config);
        for ($i=0; $i < 20; $i++) { 
            $data = \DB::table('users_withdrawal')->where('status', 4)->orderBy('id', 'asc')
            ->select(['id', 'transaction_no'])->first();
            if( !$data ){
                sleep(1);
            }else{
                $res = $app->transfer->queryBalanceOrder($data->transaction_no);
                if( !isset($res['return_code']) || !isset($res['result_code']) ){
                    continue;
                }
                if( $res['return_code'] == 'SUCCESS' ){
                    
                    if( isset($res['status']) && $res['status'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS' ){
                        //成功
                        $paymentService = new PaymentService();
                        $paymentService->withdrawalResult($data->transaction_no, 1, isset($res['detail_id'])?$res['detail_id']:'');
                        continue;
                    }elseif( ( $res['result_code'] == 'FAIL' && !isset($res['status']) ) || ( isset($res['status']) && $res['status'] == 'FAILED' ) ){
                        //失败
                        $paymentService = new PaymentService();
                        $paymentService->withdrawalResult($data->transaction_no, 0, isset($res['detail_id'])?$res['detail_id']:'');
                        continue;
                    }
                }
            }
        }
    }

    /**
     * 商户待结算检查    00：00执行
     */
    public static function notSettleCheck()
    {
        $d = date('Y-m-d 00:00:00', strtotime('-1 day', time()));
        set_time_limit(200);
        InterfaceLog('notSettleCheck', '商户待结算检查');
        $list = \DB::table('users')->where([
            ['type', 1],
            ['merchant_status', 1],
        ])->whereNull('frozen_date')->select(['id'])->get()->toArray();
        if( count($list) ){
            foreach ($list as $key => $value) {
                try{
                    \DB::beginTransaction();
                    $count = \DB::table('users_orders')->where('store_uid', $value->id)->whereIn('status', [40,35])->where('created_at', '<', $d)->count();
                    if( $count ){
                        //有待结算订单
                        \DB::table('users')->where('id', $value->id)->update(['frozen_date'=>getDt(), 'updated_at'=>getDt()]);
                        \DB::table('subsidy')->where('uid', $value->id)->update(['is_frozen'=>1, 'updated_at'=>getDt()]);
                    }
                    \DB::commit();
                }catch( \Exception $exception ){
                    InterfaceLog('notSettleCheck', $exception->getMessage());
                    \DB::rollBack();
                }
                if( $count ){
                    try {
                        UserService::sendMiniSoftMsg(DB::table('users')->where('id', $value->id)->value('openid'), 1, "pages/store/orderlist?type=1", [
                            "thing1"=>['value'=>"已暂停下单"],
                            "thing2"=>['value'=>$count],
                            "time3"=>['value'=>getDt()],
                            "thing4"=>['value'=>"任务已暂停下单，请及时处理复审恢复任务"],
                        ]);
                    } catch (\Exception $exception) {
                        InterfaceLog('notSettleCheck', $exception->getMessage());
                    }
                    
                }
            }
        }
    }

}